const User = require('../models/User');
const { Op } = require('sequelize');

// 管理员获取所有用户
exports.getAllUsers = async (req, res) => {
  try {
    const { role, status, keyword, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    const whereClause = {};

    if (role) whereClause.role = role;
    if (status !== undefined) whereClause.status = status;
    if (keyword) {
      whereClause[Op.or] = [
        { username: { [Op.like]: `%${keyword}%` } },
        { email: { [Op.like]: `%${keyword}%` } },
        { companyName: { [Op.like]: `%${keyword}%` } }
      ];
    }

    const { count, rows: users } = await User.findAndCountAll({
      where: whereClause,
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']],
      attributes: { exclude: ['password'] }
    });

    res.status(200).json({
      success: true,
      data: {
        users,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          pages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    });
  }
};

// 管理员获取单个用户详情
exports.getUserById = async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.status(200).json({
      success: true,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户详情失败',
      error: error.message
    });
  }
};

// 管理员更新用户状态（审核/封禁）
exports.updateUserStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    await user.update({ status });

    res.status(200).json({
      success: true,
      message: '用户状态更新成功',
      data: { id: user.id, status: user.status }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新用户状态失败',
      error: error.message
    });
  }
};

// 管理员更新用户角色
exports.updateUserRole = async (req, res) => {
  try {
    const { id } = req.params;
    const { role } = req.body;

    // 防止修改管理员自身角色
    if (req.user.id === parseInt(id) && role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '不能修改自身管理员角色'
      });
    }

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    await user.update({ role });

    res.status(200).json({
      success: true,
      message: '用户角色更新成功',
      data: { id: user.id, role: user.role }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新用户角色失败',
      error: error.message
    });
  }
};

// 管理员删除用户
exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;

    // 防止删除管理员自身
    if (req.user.id === parseInt(id)) {
      return res.status(403).json({
        success: false,
        message: '不能删除自身账号'
      });
    }

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    await user.destroy();
    res.status(200).json({
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除用户失败',
      error: error.message
    });
  }
};

// 获取企业资料
exports.getCompanyProfile = async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: { exclude: ['password'] }
    });

    res.status(200).json({
      success: true,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取企业资料失败',
      error: error.message
    });
  }
};

// 更新企业资料
exports.updateCompanyProfile = async (req, res) => {
  try {
    const userId = req.user.id;
    const { companyName, industry,规模, address, description, logo } = req.body;

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    await user.update({
      companyName,
      industry,
     规模,
      address,
      description,
      logo
    });

    res.status(200).json({
      success: true,
      message: '企业资料更新成功',
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新企业资料失败',
      error: error.message
    });
  }
};

// 获取求职者资料
exports.getJobSeekerProfile = async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: { exclude: ['password'] }
    });

    res.status(200).json({
      success: true,
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取求职者资料失败',
      error: error.message
    });
  }
};

// 更新求职者资料
exports.updateJobSeekerProfile = async (req, res) => {
  try {
    const userId = req.user.id;
    const { fullName, phone, avatar } = req.body;

    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    await user.update({
      fullName,
      phone,
      avatar
    });

    res.status(200).json({
      success: true,
      message: '求职者资料更新成功',
      data: user
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新求职者资料失败',
      error: error.message
    });
  }
};